package com.webchat.ugc.service.chain;

import com.webchat.common.util.web.UrlAnalysisUtil;
import com.webchat.domain.dto.UrlAnalysisResultDTO;
import com.webchat.domain.vo.response.moment.MomentLinkVO;
import com.webchat.domain.vo.response.moment.MomentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Component
public class MomentLinkHandler implements MomentPublishHandler {


    @Override
    public void handle(MomentVO moment, MomentPublishHandlerChain chain) {

        if (!ObjectUtils.equals(moment.getIncludeLink(), true)) {
            chain.handle(moment, chain);
            return;
        }
        this.doUrlAnalysisByJsonp(moment.getLink());
        chain.handle(moment, chain);
    }

    /**
     * 链接分享同学圈，支持链接解析
     *
     * @param link
     */
    private void doUrlAnalysisByJsonp( MomentLinkVO link) {

        UrlAnalysisResultDTO result = UrlAnalysisUtil.analyze(link.getResource());
        if (result == null) {
            return;
        }
        link.setTitle(result.getTitle());
        link.setCover(StringUtils.isNotBlank(result.getFirstImage()) ?
                result.getFirstImage() : result.getIcon());
    }
}
